package com.hutu.service.biz.impl;

import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition;
import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement;
import com.alibaba.druid.sql.ast.statement.SQLPrimaryKey;
import com.alibaba.druid.sql.ast.statement.SQLTableElement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlCreateTableParser;
import com.hutu.core.config.BusinessException;
import com.hutu.core.enums.system.BusinessStatusEnum;
import com.hutu.core.sql.MySQLDialect;
import com.hutu.model.entity.core.ColumnInfo;
import com.hutu.model.entity.core.TableInfo;
import com.hutu.service.biz.SqlService;
import com.hutu.service.biz.TableInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class SqlServiceImpl implements SqlService {

    private static final MySQLDialect sqlDialect = new MySQLDialect();

    @Resource
    private TableInfoService tableInfoService;

    @Override
    public TableInfo parseSql(String sql) {
        if (StringUtils.isBlank(sql)) {
            throw new BusinessException(BusinessStatusEnum.NOT_EXIST);
        }

        TableInfo tableSchema = new TableInfo();


        try {
            // 解析 SQL
            MySqlCreateTableParser parser = new MySqlCreateTableParser(sql);
            SQLCreateTableStatement sqlCreateTableStatement = parser.parseCreateTable();

            //设置表名
            tableSchema.setTableName(sqlDialect.parseTableName(sqlCreateTableStatement.getTableName()));
            String tableComment = null;
            if (sqlCreateTableStatement.getComment() != null) {
                tableComment = sqlCreateTableStatement.getComment().toString();
                if (tableComment.length() > 2) {
                    tableComment = tableComment.substring(1, tableComment.length() - 1);
                }
            }
            //设置表注释
            tableSchema.setTableComment(tableComment);

            List<ColumnInfo> fieldList = tableSchema.getColumns();
            // 解析列
            for (SQLTableElement sqlTableElement : sqlCreateTableStatement.getTableElementList()) {
                // 主键约束
                if (sqlTableElement instanceof SQLPrimaryKey) {
                    SQLPrimaryKey sqlPrimaryKey = (SQLPrimaryKey) sqlTableElement;
                    String primaryFieldName = sqlDialect.parseFieldName(sqlPrimaryKey.getColumns().get(0).toString());
                    fieldList.forEach(field -> {
                        if (field.getColumnName().equals(primaryFieldName)) {
                            field.setPrimaryKey(true);
                        }
                    });
                } else if (sqlTableElement instanceof SQLColumnDefinition) {
                    // 列
                    SQLColumnDefinition columnDefinition = (SQLColumnDefinition) sqlTableElement;
                    ColumnInfo field = new ColumnInfo();
                    //列名
                    field.setColumnName(sqlDialect.parseFieldName(columnDefinition.getNameAsString()));
                    //字段类型
                    field.setColumnType(columnDefinition.getDataType().toString());
                    String defaultValue = null;
                    if (columnDefinition.getDefaultExpr() != null) {
                        defaultValue = columnDefinition.getDefaultExpr().toString();
                    }
                    field.setDefaultValue(defaultValue);
                    field.setNotNull(columnDefinition.containsNotNullConstaint());
                    String comment = null;
                    if (columnDefinition.getComment() != null) {
                        comment = columnDefinition.getComment().toString();
                        if (comment.length() > 2) {
                            comment = comment.substring(1, comment.length() - 1);
                        }
                    }
                    field.setColumnComment(comment);
                    field.setPrimaryKey(columnDefinition.isPrimaryKey());
                    field.setAutoIncrement(columnDefinition.isAutoIncrement());
                    String onUpdate = null;
                    if (columnDefinition.getOnUpdate() != null) {
                        onUpdate = columnDefinition.getOnUpdate().toString();
                    }
                    field.setOnUpdate(onUpdate);
                    fieldList.add(field);
                }
            }

        }catch (Exception e){
            log.error("SQL 解析错误", e);
            throw new BusinessException(BusinessStatusEnum.PARAMS_ERROR, "请确认 SQL 语句正确");
        }


        return tableSchema;
    }
}
